//-----------------编写接口-----------------

//1 加载express
//2 创建路由队象
//3 把接口挂在到路由对象上
//4 导出路由
//5 app.js 加载模块
const path = require('path');
const db = require(path.join(__dirname,'../db'));
const express = require('express');
const router = express.Router();
//获取书籍接口
router.get('/getbooks',async (req,res) => {
    // db('select * from book',null,(err,result) => {
    //     if(err) return console.log(err);
    //     //查询总的记录数
    // db('select count(*) total from book',null,(e,r) => {
    //     res.send({ 
    //         status: 200,
    //         msg: '获取成功',
    //         data: result,
    //         total: r[0].total
    //     });
    // });
    // });
    // let r1 = await db('select * from book where id>?',2);
    // let r2 = await db('select count(*) total from book',null);
    // res.send({ 
    //     status: 200,
    //     msg: '获取成功',
    //     data: r1,
    //     total: r2[0].total
    // });
    let r1 = await db('select * from book where id>?',42);
    let r2 = await db('select count(*) total from book',null);
    res.send({ 
            status: 200,
            msg: '获取成功',
            data: r1,
            total: r2[0].total
        });
});

//添加书籍接口
router.post('/addbook',async(req,res) => {
    // console.log(req.body)
    // db('insert into book set ?',req.body,(err,result) => {
    //     if(err || result.affectedRows <=0) {
    //         res.send({status:500,msg:"添加失败"});
    //     }else{
    //         res.send({status: 201,msg:"添加成功"})
    //     }
    // });
    let r = await db('insert into book set ?',req.body);
    res.send({stats:200,msg:'添加成功'});
});

//删除书记接口
router.get('/delbook',async (req,res) => {
    let id = req.query.id;
    // 
    // db('delete from book where id=?',id,(err,result) => {
    //     if(err || result.affectedRows <= 0) {
    //         res.send({status:500,msg:"删除失败"});
    //     }else{
    //         res.send({status: 201,msg:"删除成功"})
    //     }
    // });
    let r = await db('delete from book where id=?',id);
    res.send({status:200,msg:'删除成功'})
}); 

module.exports = router;